from django.shortcuts import render,HttpResponseRedirect
from Buyer.models import *
from Store.models import *
from Qshop.views import setPassword


def login(request):
    if request.method == "POST":
        data = request.POST
        username = data.get("username")
        password = data.get("password")

        user = QUser.objects.filter(
            username=username,
            password=setPassword(password),
            has_store=1
        ).first()
        if user:
            response = HttpResponseRedirect("/store/index/")
            response.set_cookie("user_id", user.id)
            response.set_cookie("username", user.username)
            request.session["user_id"] = user.id
            return response
    return render(request, "store/login.html")


def index(request):
    return render(request, "store/index.html")


def goods(request):
    t_list = GoodsType.objects.all()
    user_id = request.COOKIES.get("user_id")
    user = QUser.objects.get(id=user_id)
    store = user.store
    if request.method == "POST":
        data = request.POST
        goods_name = data.get("goods_name")
        goods_type = data.get("goods_type")
        g_price = data.get("g_price")
        g_safe_date = data.get("g_safe_date")
        g_public_date = data.get("g_public_date")
        goods_number = data.get("goods_number")
        g_description = data.get("g_description")
        g_picture = request.FILES.get("g_picture")
        desc_content = data.get("desc_content")
        save_unit = data.get("save_unit")

        goods = Goods()
        goods.goods_name = goods_name
        goods.goods_price = g_price

        goods.goods_number = goods_number
        goods.save_time = g_safe_date
        goods.save_unit = save_unit
        goods.publish_time = g_public_date
        goods.goods_description = g_description
        goods.picture = g_picture
        goods.desc_content = desc_content
        goods.g_type = GoodsType.objects.get(id=int(goods_type))
        goods.g_store = Store.objects.get(id=store.id)
        goods.save()
        goods.goods_id = str(goods.id).zfill(8)
        goods.save()
    goods_list = store.goods_set.all()
    return render(request, "store/goods.html", locals())


def statistics_goods(request):
    return render(request, 'store/statistics_goods.html')


def orders(request):

    return render(request, 'store/orders.html')


def statistics_orders(request):
    return render(request, 'store/statistics_orders.html')

# Create your views here.
